package io.renren.cloud;

import com.aliyun.oss.HttpMethod;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.GeneratePresignedUrlRequest;
import com.aliyun.oss.model.OSSObject;
import io.renren.commons.tools.exception.RenException;
import io.renren.exception.ModuleErrorCode;
import io.renren.vo.StsTokenVO;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.net.URL;
import java.util.*;

public class AliyunStsCloudStorageService extends AbstractCloudStorageService {
    private StsCloudStorageConfig config;
    private StsTokenVO stsTokenVO;
    public AliyunStsCloudStorageService(StsCloudStorageConfig config,StsTokenVO stsTokenVO){
        this.config = config;
        this.stsTokenVO=stsTokenVO;
    }

    @Override
    public String upload(byte[] data, String path) {
        return upload(new ByteArrayInputStream(data), path);
    }

    @Override
    public String uploadSuffix(byte[] data, String suffix) {
        return upload(data, getPath(config.getPrefix(), suffix));
    }

    @Override
    public String upload(InputStream inputStream, String path) {
        OSSClient client = new OSSClient(config.getEndpoint(), stsTokenVO.getAccessKeyId(),stsTokenVO.getSecretAccessKey(), stsTokenVO.getSecurityToken());
        try {
            client.putObject(config.getBucketname(), path, inputStream);
            client.shutdown();
        } catch (Exception e){
            throw new RenException(ModuleErrorCode.OSS_UPLOAD_FILE_ERROR, e, "");
        }
        return config.getDomain() + "/" + path;
    }

    @Override
    public String uploadSuffix(InputStream inputStream, String suffix) {
        return upload(inputStream, getPath(config.getPrefix(), suffix));
    }

    public List<URL> download(List<String> keys){
        OSSClient client = new OSSClient(config.getEndpoint(), stsTokenVO.getAccessKeyId(),stsTokenVO.getSecretAccessKey(), stsTokenVO.getSecurityToken());
        // 指定生成的签名URL过期时间，单位为毫秒。
        Date expiration = new Date(new Date().getTime() + 3600 * 1000);
        Map<String, String> headers = new HashMap<>();
        // 如果您希望直接在浏览器中预览文件，配置文件HTTP头中的Content-Disposition为inline并使用Bucket绑定的自定义域名进行访问。
        headers.put("content-disposition","inline");
        // 通过HTTP GET请求生成签名URL。
        List<URL> urlList = new ArrayList<>();
        for(String key:keys){
            // 生成签名URL。
            GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(config.getBucketname(), key, HttpMethod.GET);
            // 设置过期时间。
            request.setExpiration(expiration);
            request.setHeaders(headers);
            URL signedUrl =client.generatePresignedUrl(request);
            urlList.add(signedUrl);
        }
        client.shutdown();
        return urlList;
    }
}
